/*
 * Copyright 2017-2021 Pranav Pandey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pranavpandey.ohos.dynamic.toasts.watcher;


import ohos.agp.components.AttrHelper;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.Optional;

/**
 * Helper class to perform unit conversions.
 */
public class DynamicUnitUtils {
    /**
     * Converts DP into pixels.
     *
     * @param context 上下文
     * @param dp The value in DP to be converted into pixels.
     * @return The converted value in pixels.
     */
    public static int convertDpToPixels(Context context, float dp) {
        return AttrHelper.vp2px(dp, AttrHelper.getDensity(context));
    }

    /**
     * Converts pixels into DP.
     *
     * @param context 上下文
     * @param pixels The value in pixels to be converted into DP.
     * @return The converted value in DP.
     */
    public static int convertPixelsToDp(Context context,float pixels) {
        Optional<Display> optional = DisplayManager.getInstance().getDefaultDisplay(context);
        DisplayAttributes attributes = optional.get().getAttributes();
        return Math.round(pixels / attributes.scalDensity);
    }

    /**
     * Converts SP into pixels.
     *
     * @param context 上下文
     * @param sp The value in SP to be converted into pixels.
     *
     * @return The converted value in pixels.
     */
    public static float convertSpToPixels(Context context, float sp) {
        return AttrHelper.fp2px(sp, AttrHelper.getDensity(context));
    }

    /**
     * Converts pixels into SP.
     *
     * @param context 上下文
     * @param pixels The value in pixels to be converted into SP.
     *
     * @return The converted value in SP.
     */
    public static float convertPixelsToSp(float pixels,Context context) {
        Optional<Display> display =  DisplayManager.getInstance().getDefaultDisplay(context);
        DisplayAttributes attributes =  display.get().getAttributes();
        return Math.round(pixels / attributes.scalDensity);
    }

    /**
     * Converts DP into SP.
     * @param context 上下文
     * @param dp The value in DP to be converted into SP.
     *
     * @return The converted value in SP.
     */
    public static float convertDpToSp(Context context,float dp) {
        return Math.round(convertDpToPixels(context,dp) / convertSpToPixels(context,dp));
    }
}
